package br.com.lumis.saas.service.consumerclient.processaction;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.util.XmlUtil;
import lumis.util.log.ILogger;
import lumis.util.log.LoggerFactory;
import br.com.lumis.saas.SaasRequestParameters;
import br.com.lumis.saas.service.consumerclient.model.Customer;
import br.com.lumis.saas.service.consumerclient.model.Environment;
import br.com.lumis.saas.service.consumerclient.persistence.dao.CustomerDAO;
import br.com.lumis.saas.service.consumerclient.persistence.dao.EnvironmentDAO;
import br.com.lumis.saas.util.Configuration;

@SuppressWarnings("unchecked")
public class CreateEnvironmentProcessActionHandler extends
		ProcessActionHandler<Source> {
	private static final ILogger logger = LoggerFactory.getLogger(CreateEnvironmentProcessActionHandler.class);
	private static final String ENVIRONMENT_ADD = "addEnvironment";
	private static final String RESTORE_BACKUP = "restoreBackup";
	private CustomerDAO customerDAO = new CustomerDAO();
	private EnvironmentDAO environmentDAO = new EnvironmentDAO();
	private Configuration config;
	
	
	public void processAction() throws PortalException {
		String actionType = XmlUtil.readAttributeString(
				SaasRequestParameters.ACTIONTYPE, processActionNode, "");
		
		config = Configuration.getInstance();
		
		if (actionType.equals(ENVIRONMENT_ADD))
			processAddEnvironment();
		else if (actionType.equals(RESTORE_BACKUP))
			processRestoreBackup();
		else if (actionType.equals("updateEnvironment"))
			processUpdateEnvironment();

	}

	private void processUpdateEnvironment() throws PortalException {
		String environmentId = (String) getParameter(SaasRequestParameters.ENVIRONMENTID);
		
		Environment environment = environmentDAO.get(environmentId, transaction);
		
		String name = "";
		
		if(environment.getType()==1)											
			name = "saas-"+environment.getCustomer().getSurname().toLowerCase() +"-app";
		else if(environment.getType()==2) 
			name = "saas-"+environment.getCustomer().getSurname().toLowerCase() +"-dev";				
		else if(environment.getType()==3){
			int sufix = environment.getSufix();
			name = "saas-"+environment.getCustomer().getSurname().toLowerCase() +"-app-" +sufix ;										
		}
		
		environmentDAO.updateName(environmentId,  name,  transaction);
		addDefaultResponse();
	}

	private void processRestoreBackup() throws PortalException {
		String datebucket = (String) getParameter(SaasRequestParameters.DATABUCKET);
		String environmentId = (String) getParameter(SaasRequestParameters.ENVIRONMENTID);

		try {
			Environment environmentConfig = environmentDAO.get(environmentId,
					transaction);
			if (datebucket == null || datebucket.equals(""))
				throw new PortalException("Data com valor null");

			
						
			String url = config.getProperty("saas.environment.url.restore") + environmentConfig.getCustomer().getSurname() +"&date=" + datebucket;						

			boolean ok = createMachine(url);

			if (!ok)
				throw new PortalException(
						localize("STR_ERROR_ADD_ENVIRONMENT_AMAZON"));

			addDefaultResponse();

		} catch (MalformedURLException e) {
			throw new PortalException(
					localize("STR_ERROR_ADD_ENVIRONMENT_AMAZON"));
		} catch (IOException e) {
			throw new PortalException(
					localize("STR_ERROR_ADD_ENVIRONMENT_AMAZON"));
		}
	}
	/**
	 * 
	 * @throws PortalException
	 */
	private void processAddEnvironment() throws PortalException {
		try {			
			String site = (String) getParameter(SaasRequestParameters.URL);
			String customerId = (String) getParameter(SaasRequestParameters.PAGE_PARAMETER_CUSTOMERID);
			int type = Integer.valueOf(getParameter(SaasRequestParameters.TYPE, String.class));
			int sufix = Integer.valueOf(getParameter(SaasRequestParameters.SUFIX, String.class));

			Customer customer = customerDAO.getById(customerId, transaction);
			String customerSurname = customer.getSurname();
			String url ="";
			
			if(type ==1)			
				url = config.getProperty("saas.environment.url.create") + customerSurname +"&site=" + site;							
			else if (type==2)
				url = config.getProperty("saas.environment.url.createdev") + customerSurname +"&site=" + site;													
			else if(type==3)
				url = config.getProperty("saas.environment.url.createapp") + customerSurname +"&sufix=" + sufix;
			
			logger.info(url);
			
			boolean ok = createMachine(url);

			if (!ok)
				throw new PortalException(
						localize("STR_ERROR_ADD_ENVIRONMENT_AMAZON"));
			
			addDefaultResponse();

		} catch (MalformedURLException e) {
			throw new PortalException(
					localize("STR_ERROR_ADD_ENVIRONMENT_AMAZON"));
		} catch (IOException e) {
			throw new PortalException(
					localize("STR_ERROR_ADD_ENVIRONMENT_AMAZON"));
		}
	}

	private boolean createMachine(String url) throws MalformedURLException,
			IOException {
		URL oracle;

		oracle = new URL(url);

		URLConnection yc = oracle.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(yc
				.getInputStream()));
		String inputLine;

		boolean ok = false;

		while ((inputLine = in.readLine()) != null)
			if (inputLine.equals("finished"))
				ok = true;

		in.close();
		return ok;
	}
}
